import Vue from "vue";
import '../../public/jsToUe';

export function sendMsg(data) {
    return new Promise(resolve => {
        ue.call('FSUE', data, (res) => {
            resolve(res)
            console.log("发送消息：" + res);
        });
    });
}

export function createCursorImg(
  operateType,
  imgUrl,
  width,
  height,
  e,
  offsetX,
  offsetY,
  className
) {
  let style = document.createElement("style");
  style.type = "text/css";
  style.className = "cursor-style";
  let cssContent = document.createTextNode("* { cursor: none !important; }");
  style.appendChild(cssContent);
  document.head.appendChild(style);
  const oImg = document.createElement("img");
  oImg.src = require(`../assets/images/${imgUrl}`);
  oImg.className = `cursor-img ${className}`;
  oImg.style.width = width + "px";
  oImg.style.height = height + "px";
  oImg.style.position = "absolute";
  oImg.style.pointerEvents = "none";
  oImg.style.zIndex = 10000;
  oImg.style.left = e.clientX + offsetX + "px";
  oImg.style.top = e.clientY + offsetY + "px";
  document.body.appendChild(oImg);

  document.body.addEventListener("mousemove", (e) => {
    oImg.style.left = e.clientX + offsetX + "px";
    oImg.style.top = e.clientY + offsetY + "px";
  });

  document.body.addEventListener("contextmenu", (e) => {
    e.preventDefault();
    document.head.getElementsByClassName("cursor-style")[0]?.remove();
    document.body.getElementsByClassName("cursor-img")[0]?.remove();
    document.body.getElementsByClassName("red-multimeter")[0]?.remove();
    document.body.getElementsByClassName("black-multimeter")[0]?.remove();
    localStorage.removeItem("OPERATE-STATUS");
  });
  localStorage.setItem("OPERATE-STATUS", operateType);
}
export function removeCursorImg() {
  document.head.getElementsByClassName("cursor-style")[0]?.remove();
  document.body.getElementsByClassName("cursor-img")[0]?.remove();
}

export function initLinePosition(dataList) {
  dataList.forEach((item) => {
    item.indicatorDataList.forEach((o, i) => {
      o.lineKey = item.lineList[i].key;
      o.lineLeft = i % 2 === 0 ? "30px" : "130px";
      o.lineTop = Math.floor(i / 2) * 33 + 14 + "px";
    });
  });
  [...document.getElementsByClassName("terminal-item")].forEach((item) => {
    const lines = [...item.getElementsByClassName("line-item")];
    lines.forEach((item, i) => {
      item.style.left = i % 2 === 0 ? "30px" : "130px";
      item.style.top = Math.floor(i / 2) * 33 + 14 + "px";
    });
  });
  document.body.addEventListener("contextmenu", (e) => {
    e.preventDefault();
    document.head.getElementsByClassName("cursor-style")[0]?.remove();
    document.body.getElementsByClassName("cursor-img")[0]?.remove();
    localStorage.removeItem("OPERATE-STATUS");
  });
}

export function initIndicatorStatus(dataList) {
  dataList.forEach((item) => {
    const upLines = [];
    item.lineList.forEach((o) => {
      if (o.state == 0) {
        upLines.push(o.key);
      }
    });
    upLines.forEach((o) => {
      item.indicatorDataList.find((u) => u.lineKey == o).state = 1;
    });
  });
}
function removePxHandler(value) {
  return +value.slice(0, value.length - 2);
}
export function clickIndicatorHandler(dataList, data, index, parent, e) {
  // 螺丝刀
  if (localStorage.getItem("OPERATE-STATUS") === "screwdriver") {
    if (data.state === 0) {
      // 弹出线
      const aLines =
        e.target.parentNode.parentNode.parentNode.getElementsByClassName(
          "line-item"
        );
      const lineNode = [...aLines].find((o) => {
        const arr = o.getAttribute("lineKey").split("-");
        return arr[arr.length - 1] == data.lineKey;
      });
      const removePx = index % 2 === 0 ? -20 : 20;
      lineNode.style.left =
        removePxHandler(lineNode.style.left) + removePx + "px";
      // 指示灯状态
      data.state = data.state == 1 ? 0 : 1;
      lineNode.style.zIndex = data.state === 1 ? 100 : -1;
      // 设置线状态
      let lineData = parent.lineList.find((o) => {
        const arr = lineNode.getAttribute("lineKey").split("-");
        return o.key == arr[arr.length - 1];
      });
      lineData.state = lineData.state == 0 ? 1 : 0;
    } else {
      // 接线
      const aImgs = [...document.getElementsByClassName("terminal-bar")];
      const activeImgNode = aImgs.find((o) => o.className.includes("active"));
      if (!!activeImgNode) {
        // 将线挂到孔上
        const arr = activeImgNode.parentNode.getAttribute("lineKey").split("-");
        data.lineKey = arr[arr.length - 1];
        const currentLine = activeImgNode.parentNode;
        currentLine.style.left = data.lineLeft;
        currentLine.style.top = data.lineTop;
        // 去掉线active状态
        activeImgNode.className = "terminal-bar";
        currentLine.style.zIndex = -1;
        // 设置线状态
        let lineData = parent.lineList.find((o) => {
          return o.key == data.lineKey;
        });
        lineData.state = lineData.state == 0 ? 1 : 0;
        // 指示灯状态
        data.state = data.state == 1 ? 0 : 1;
      } else {
        Vue.prototype.$message.warning("请选择接线");
      }
    }
  } else if (localStorage.getItem("OPERATE-STATUS") === "multimeter") {
    // 万用表
    if (document.getElementsByClassName("cursor-img")[0]) {
      if (e.target.className.includes("indicator-dot")) {
        const multimeter = document.createElement("img");
        multimeter.style.width = "22px";
        multimeter.style.height = "80px";
        multimeter.style.position = "absolute";
        multimeter.style.zIndex = 1000;
        multimeter.style.cursor = "pointer";
        multimeter.setAttribute("wybValue", data.wybValue);
        if (!!document.getElementsByClassName("red-multimeter-cursor")[0]) {
          multimeter.src = require("../assets/images/protect-screen/multimeter/red.png");
          multimeter.className = "red-multimeter";
        } else {
          multimeter.src = require("../assets/images/protect-screen/multimeter/black.png");
          multimeter.className = "black-multimeter";
        }
        if (index % 2 === 0) {
          multimeter.style.left = removePxHandler(data.lineLeft) + 40 + "px";
          multimeter.style.top = removePxHandler(data.lineTop) - 6 + "px";
        } else {
          multimeter.style.left = removePxHandler(data.lineLeft) - 10 + "px";
          multimeter.style.top = removePxHandler(data.lineTop) - 6 + "px";
        }
        e.target.parentNode.parentNode.parentNode.appendChild(multimeter);
        removeCursorImg();
        dataList.forEach((item) => {
          item.indicatorDataList.forEach((o) => {
            o.state = 0;
          });
        });
        multimeter.addEventListener("click", function (e) {
          this.remove();
          if (e.target.className.includes("red")) {
            selectRedMultimeter(dataList, e);
          } else {
            selectBlackMultimeter(dataList, e);
          }
        });
      }
    } else {
      Vue.prototype.$message.warning("请先拾取工具");
    }
  } else {
    Vue.prototype.$message.warning("请先拾取工具");
  }
}

export function selectLineHandler(e) {
  if (localStorage.getItem("OPERATE-STATUS") === "screwdriver") {
    const aImgs = [...document.getElementsByClassName("terminal-bar")];
    aImgs.forEach((item) => {
      item.className = "terminal-bar";
    });
    if (e.target.className.includes("active")) {
      e.target.className = "terminal-bar";
    } else {
      e.target.className = "terminal-bar active";
    }
  } else {
    Vue.prototype.$message.warning("请先拾取工具");
  }
}

export function selectRedMultimeter(dataList, e) {
  if (!document.getElementsByClassName("red-multimeter")[0]) {
    removeCursorImg();
    createCursorImg(
      "multimeter",
      "protect-screen/multimeter/red.png",
      18,
      75,
      e,
      -10,
      -10,
      "red-multimeter-cursor"
    );
    dataList.forEach((item) => {
      item.indicatorDataList.forEach((o) => {
        o.state = 1;
      });
    });
    document.body.addEventListener("contextmenu", (e) => {
      e.preventDefault();
      dataList.forEach((item) => {
        item.indicatorDataList.forEach((o) => {
          o.state = 0;
        });
      });
    });
  }
}
export function selectBlackMultimeter(dataList, e) {
  if (!document.getElementsByClassName("black-multimeter")[0]) {
    removeCursorImg();
    createCursorImg(
      "multimeter",
      "protect-screen/multimeter/black.png",
      18,
      75,
      e,
      -10,
      -10,
      "black-multimeter-cursor"
    );
    dataList.forEach((item) => {
      item.indicatorDataList.forEach((o) => {
        o.state = 1;
      });
    });
    document.body.addEventListener("contextmenu", (e) => {
      e.preventDefault();
      dataList.forEach((item) => {
        item.indicatorDataList.forEach((o) => {
          o.state = 0;
        });
      });
    });
  }
}

export function startCheckKnob(e) {
  if (e.target.className.includes("knob")) {
    if (
      !document.getElementsByClassName("red-multimeter")[0] ||
      !document.getElementsByClassName("black-multimeter")[0]
    ) {
      Vue.prototype.$message.warning("请先接线");
      return;
    }
    let rotate = 0;
    let dw = "gj";
    if (!!e.target.style.transform) {
      const startIndex = e.target.style.transform.indexOf("(") + 1;
      const endIndex = e.target.style.transform.indexOf("deg");
      rotate = +e.target.style.transform.slice(startIndex, endIndex);
    }
    if (rotate === 0) {
      rotate += 20;
      dw = "dy_jl";
    } else if (rotate === 20) {
      rotate += 20;
      dw = "dy_zl";
    } else if (rotate === 40) {
      rotate += 50;
      dw = "dz";
    } else {
      rotate = 0;
      dw = "gj";
    }
    e.target.style.transform = `rotate(${rotate}deg)`;
    Vue.prototype.$bus.$emit("sendMessage", {
      cmd: "wybTest",
      dw,
      redPoint: document
        .getElementsByClassName("red-multimeter")[0]
        ?.getAttribute("wybValue"),
      blackPoint: document
        .getElementsByClassName("black-multimeter")[0]
        ?.getAttribute("wybValue"),
      jgName: localStorage.getItem("jgName"),
      deviceName: localStorage.getItem("deviceName"),
    });
  }
}

export function clickDiHandler(e) {
  if (document.getElementsByClassName("cursor-img")[0]) {
    if (e.target.tagName.includes("IMG")) {
      const multimeter = document.createElement("img");
      multimeter.style.width = "26px";
      multimeter.style.height = "110px";
      multimeter.style.position = "absolute";
      multimeter.style.zIndex = 1000;
      multimeter.style.cursor = "pointer";
      multimeter.setAttribute("wybValue", "JD");
      if (!!document.getElementsByClassName("red-multimeter-cursor")[0]) {
        multimeter.src = require("../assets/images/protect-screen/multimeter/red.png");
        multimeter.className = "red-multimeter";
      } else {
        multimeter.src = require("../assets/images/protect-screen/multimeter/black.png");
        multimeter.className = "black-multimeter";
      }
      multimeter.style.left = "328px";
      multimeter.style.bottom = "20px";
      e.target.parentNode.parentNode.parentNode.appendChild(multimeter);
      removeCursorImg();
      multimeter.addEventListener("click", function (e) {
        this.remove();
        if (e.target.className.includes("red")) {
          selectRedMultimeterAgain(e);
        } else {
          selectBlackMultimeterAgain(e);
        }
      });
    }
  }
}

function selectRedMultimeterAgain(e) {
  if (!document.getElementsByClassName("red-multimeter")[0]) {
    removeCursorImg();
    createCursorImg(
      "multimeter",
      "protect-screen/multimeter/red.png",
      18,
      75,
      e,
      -10,
      -10,
      "red-multimeter-cursor"
    );
  }
}

function selectBlackMultimeterAgain(e) {
  if (!document.getElementsByClassName("black-multimeter")[0]) {
    removeCursorImg();
    createCursorImg(
      "multimeter",
      "protect-screen/multimeter/black.png",
      18,
      75,
      e,
      -10,
      -10,
      "black-multimeter-cursor"
    );
  }
}

export function selectScrewdriverHandler(e) {
  removeCursorImg();
  createCursorImg(
    "screwdriver",
    "protect-screen/screwdriver.png",
    100,
    100,
    e,
    -10,
    -30,
    "screwdriver-cursor"
  );
  // 高亮已经拔出的线孔
  Vue.prototype.$bus.$emit("init-indicator-state");
}

export function selectMultimeterHandler() {
  removeCursorImg();
  localStorage.setItem("OPERATE-STATUS", "multimeter");
  Vue.prototype.$bus.$emit("change-multimeter", true);
  document.body.addEventListener("contextmenu", (e) => {
    e.preventDefault();
    Vue.prototype.$bus.$emit("change-multimeter", false);
  });
}
export function getCurrentDate() {
  const d = new Date();
  const year = d.getFullYear();
  let month = d.getMonth() + 1;
  let date = d.getDate();
  if (month < 10) {
    month = "0" + month;
  }
  if (date < 10) {
    date = "0" + date;
  }
  return year + "-" + month + "-" + date;
}

export function getCurrentTime() {
  const d = new Date();
  let hour = d.getHours();
  let minutes = d.getMinutes();
  let seconds = d.getSeconds();
  if (hour < 10) {
    hour = "0" + hour;
  }
  if (minutes < 10) {
    minutes = "0" + minutes;
  }
  if (seconds < 10) {
    seconds = "0" + seconds;
  }
  return hour + ":" + minutes + ":" + seconds;
}
export function getColorByVoltage(state, voltage) {
  // console.log(state,'state')
  // if (!!state) {
  //   return "rgb(128,128,128)";
  // } else {
    
    switch (voltage) {
      case "1000kV":
        return "rgb(0,0,255)";
      case "750kV":
        return "rgb(250,128,10)";
      case "500kV":
        return "rgb(250,0,0)";
      case "330kV":
        return "rgb(30,144,255)";
      case "220kV":
        return "rgb(128,0,128)";
      case "110kV":
        return "rgb(240,65,85)";
      case "66kV":
        return "rgb(255,204,0)";
      case "35kV":
        return "rgb(255,255,0)";
      case "20kV":
        return "rgb(226,172,6)";
      case "10kV":
        return "#59f74e";
      case "6kV":
        return "rgb(0,0, 139)";
      case "0.4kV":
        return "rgb(210,180, 140)";
    }
  // }
  // return "rgb(128,128,128)";
}
export const setList = (arr, arr2, color = "#F4FD02") => {
  let list = [];
  if (arr2.length) {
    for (let i = 0; i < arr.length; i++) {
      list.push(arr[i]);
      if (arr2[i]) {
        list.push(arr2[i]);
      }else{
        list.push({})
      }
    }
  } else if (arr.length != 1) {
    let mid = Math.floor(arr.length / 2);
    for (let i = 0; i < mid; i++) {
      list.push(arr[i]);
      list.push(arr[i + mid]);
    }
  } else {
    list = arr;
  }
  list = list.map((item) => {
    return {
      text: item.state_desc,
      circleColor: color,
      showLine: item.state_val == 1,
      ...item
    };
  });

  return list;
};
